<template>
  <div class="form-designer">
    <!-- 顶部工具栏 -->
    <div class="designer-header">
      <el-button-group>
        <el-button type="primary" @click="handleSave">
          <el-icon><Check /></el-icon>保存
        </el-button>
        <el-button @click="handleBack">
          <el-icon><Back /></el-icon>返回
        </el-button>
      </el-button-group>
      <el-button-group>
        <el-button 
          :disabled="currentHistoryIndex <= 0"
          @click="handleUndo"
        >
          <el-icon><Back /></el-icon>撤销
        </el-button>
        <el-button 
          :disabled="currentHistoryIndex >= history.length - 1"
          @click="handleRedo"
        >
          <el-icon><Right /></el-icon>重做
        </el-button>
      </el-button-group>
      <el-input
        v-model="formTitle"
        placeholder="请输入表单标题"
        class="title-input"
      />
    </div>

    <div class="designer-container">
      <!-- 左侧组件列表 -->
      <div class="components-list">
        <el-card class="component-group" v-for="group in componentGroups" :key="group.title">
          <template #header>
            <div class="group-header">{{ group.title }}</div>
          </template>
          <div class="group-content">
            <div
              v-for="item in group.items"
              :key="item.type"
              class="component-item"
              draggable="true"
              @dragstart="handleDragStart($event, item)"
            >
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.label }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 中间表单设计区域 -->
      <div
        class="form-area"
        @dragover.prevent
        @drop="handleDrop"
        ref="formAreaRef"
      >
        <el-form
          ref="formRef"
          :model="formData"
          label-width="100px"
          class="design-form"
        >
          <el-empty v-if="!formItems.length" description="拖拽组件到此处" />
          <template v-else>
            <div
              v-for="(item, index) in formItems"
              :key="index"
              class="form-item-wrapper"
              :class="{ 'is-active': currentItem === item }"
              @click="selectItem(item)"
              :ref="el => setItemRef(el, index)"
              draggable="true"
              @dragstart="handleComponentDragStart($event, item, index, 'form')"
              @dragover.prevent
              @drop="handleComponentDrop($event, index, 'form')"
            >
              <div class="drag-indicator">
                <el-icon><Rank /></el-icon>
              </div>
              <div class="form-item-actions">
                <el-button-group>
                  <el-button
                    type="primary"
                    link
                    @click.stop="moveItem(index, -1)"
                    :disabled="index === 0"
                  >
                    <el-icon><ArrowUp /></el-icon>
                  </el-button>
                  <el-button
                    type="primary"
                    link
                    @click.stop="moveItem(index, 1)"
                    :disabled="index === formItems.length - 1"
                  >
                    <el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click.stop="removeItem(index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-button-group>
              </div>
              <template v-if="item.type === 'row'">
                <div 
                  class="row-container"
                  :style="getComponentStyle(item)"
                  @dragover.prevent
                  @drop="handleRowDrop($event, item)"
                >
                  <div 
                    v-for="(rowItem, rowIndex) in item.props.items" 
                    :key="rowIndex"
                    class="row-item-wrapper"
                    :class="{ 'is-active': currentItem === rowItem }"
                    @click.stop="selectItem(rowItem)"
                    draggable="true"
                    @dragstart="handleComponentDragStart($event, rowItem, rowIndex, 'row', item)"
                    @dragover.prevent
                    @drop="handleComponentDrop($event, rowIndex, 'row', item)"
                  >
                    <div class="form-item-actions">
                      <el-button-group>
                        <el-button
                          type="primary"
                          link
                          @click.stop="moveRowItem(item, rowIndex, -1)"
                          :disabled="rowIndex === 0"
                        >
                          <el-icon><ArrowLeft /></el-icon>
                        </el-button>
                        <el-button
                          type="primary"
                          link
                          @click.stop="moveRowItem(item, rowIndex, 1)"
                          :disabled="rowIndex === item.props.items.length - 1"
                        >
                          <el-icon><ArrowRight /></el-icon>
                        </el-button>
                        <el-button
                          type="danger"
                          link
                          @click.stop="removeRowItem(item, rowIndex)"
                        >
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </el-button-group>
                    </div>
                    <el-form-item 
                      :label="rowItem.label"
                      :class="[
                        rowItem.props.labelPosition === 'top' ? 'label-top' : 'label-left'
                      ]"
                    >
                      <component
                        :is="rowItem.component"
                        v-bind="rowItem.props"
                        :placeholder="rowItem.props.placeholder"
                        :style="getComponentStyle(rowItem)"
                      />
                    </el-form-item>
                  </div>
                  <el-empty v-if="!item.props.items.length" description="拖拽组件到此处" />
                </div>
              </template>
              <template v-else-if="item.type === 'grid'">
                <el-row
                  :gutter="item.props.gutter"
                  :justify="item.props.justify"
                  :align="item.props.align"
                  :type="item.props.type"
                  class="grid-container"
                >
                  <el-col
                    v-for="(col, colIndex) in item.props.children"
                    :key="colIndex"
                    :span="24 / item.props.cols"
                    class="grid-col"
                    @dragover.prevent
                    @drop="handleGridDrop($event, item, colIndex)"
                  >
                    <div 
                      class="grid-col-content"
                      @dragover.prevent
                      @drop="handleGridDrop($event, item, colIndex)"
                    >
                      <template v-if="col.items && col.items.length">
                        <div
                          v-for="(subItem, subIndex) in col.items"
                          :key="subIndex"
                          class="form-item-wrapper"
                          :class="{ 'is-active': currentItem === subItem }"
                          @click.stop="selectItem(subItem)"
                          draggable="true"
                          @dragstart="handleComponentDragStart($event, subItem, subIndex, 'grid', item)"
                          @dragover.prevent
                          @drop="handleComponentDrop($event, subIndex, 'grid', item)"
                        >
                          <div class="form-item-actions">
                            <el-button-group>
                              <el-button
                                type="primary"
                                link
                                @click.stop="moveGridItem(item, colIndex, subIndex, -1)"
                                :disabled="subIndex === 0"
                              >
                                <el-icon><ArrowUp /></el-icon>
                              </el-button>
                              <el-button
                                type="primary"
                                link
                                @click.stop="moveGridItem(item, colIndex, subIndex, 1)"
                                :disabled="subIndex === col.items.length - 1"
                              >
                                <el-icon><ArrowDown /></el-icon>
                              </el-button>
                              <el-button
                                type="danger"
                                link
                                @click.stop="removeGridItem(item, colIndex, subIndex)"
                              >
                                <el-icon><Delete /></el-icon>
                              </el-button>
                            </el-button-group>
                          </div>
                          <el-form-item 
                            :label="subItem.label"
                            :class="[
                              subItem.props.labelPosition === 'top' ? 'label-top' : 'label-left'
                            ]"
                          >
                            <component
                              :is="subItem.component"
                              v-bind="subItem.props"
                              :placeholder="subItem.props.placeholder"
                              :style="getComponentStyle(subItem)"
                            />
                          </el-form-item>
                        </div>
                      </template>
                      <el-empty v-else description="拖拽组件到此处" />
                    </div>
                  </el-col>
                </el-row>
              </template>
              <template v-else>
                <el-form-item 
                  :label="item.label"
                  :class="[
                    item.props.labelPosition === 'top' ? 'label-top' : 'label-left'
                  ]"
                >
                  <template v-if="item.type === 'select'">
                    <el-select
                      v-model="item.props.value"
                      :placeholder="item.props.placeholder"
                      :style="getComponentStyle(item)"
                      :multiple="item.props.multiple"
                      :filterable="item.props.filterable"
                      :clearable="item.props.clearable"
                    >
                      <el-option
                        v-for="option in item.props.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                      />
                    </el-select>
                  </template>
                  <template v-else-if="item.type === 'checkbox'">
                    <div class="checkbox-group-container">
                      <div v-if="item.props.showCheckAll" class="checkbox-all">
                        <el-checkbox
                          v-model="item.props.checkAll"
                          @change="(val) => handleCheckAllChange(val, item)"
                        >全选</el-checkbox>
                      </div>
                      <div class="checkbox-list">
                        <el-checkbox
                          v-for="option in item.props.options"
                          :key="option.value"
                          v-model="item.props.value"
                          :label="option.value"
                          @change="() => handleSingleCheckChange(item)"
                        >
                          {{ option.label }}
                        </el-checkbox>
                      </div>
                    </div>
                  </template>
                  <component
                    v-else
                    :is="item.component"
                    v-bind="item.props"
                    :placeholder="item.props.placeholder"
                    :style="getComponentStyle(item)"
                  />
                </el-form-item>
              </template>
            </div>
          </template>
        </el-form>
      </div>

      <!-- 右侧属性设置面板 -->
      <div class="properties-panel">
        <el-card v-if="currentItem">
          <template #header>
            <div class="panel-header">属性设置</div>
          </template>
          <el-form label-width="80px" size="small">
            <!-- 分割线属性设置 -->
            <template v-if="currentItem.type === 'divider'">
              <!-- 1. 标签设置 -->
              <el-form-item label="标签">
                <el-input v-model="currentItem.label" placeholder="请输入标签文本" />
              </el-form-item>

              <!-- 2. 标签显示控制 -->
              <el-form-item label="显示标签">
                <el-switch v-model="currentItem.props.showLabel" />
              </el-form-item>

              <!-- 标签文本样式设置 -->
              <template v-if="currentItem.props.showLabel">
                <el-form-item label="字体">
                  <el-select v-model="currentItem.props.fontFamily">
                    <el-option label="默认" value="" />
                    <el-option label="微软雅黑" value="Microsoft YaHei" />
                    <el-option label="宋体" value="SimSun" />
                    <el-option label="黑体" value="SimHei" />
                    <el-option label="楷体" value="KaiTi" />
                  </el-select>
                </el-form-item>
                <el-form-item label="字体大小">
                  <el-input-number v-model="currentItem.props.fontSize" :min="12" :max="24" />
                </el-form-item>
                <el-form-item label="字体颜色">
                  <el-color-picker v-model="currentItem.props.fontColor" />
                </el-form-item>
              </template>

              <!-- 3. 标签位置 -->
              <el-form-item label="标签位置">
                <el-select v-model="currentItem.props.labelPosition">
                  <el-option label="顶部" value="top" />
                  <el-option label="左侧" value="left" />
                </el-select>
              </el-form-item>

              <el-divider>尺寸设置</el-divider>

              <!-- 4. 宽度设置 -->
              <el-form-item label="宽度">
                <el-select v-model="currentItem.props.widthType" class="width-type-select">
                  <el-option label="自适应" value="auto" />
                  <el-option label="固定像素" value="px" />
                  <el-option label="百分比" value="percent" />
                </el-select>
                <el-input-number 
                  v-if="currentItem.props.widthType !== 'auto'"
                  v-model="currentItem.props.width" 
                  :min="0"
                  :max="currentItem.props.widthType === 'percent' ? 100 : 2000"
                  :step="currentItem.props.widthType === 'percent' ? 5 : 10"
                  class="width-input"
                />
              </el-form-item>

              <el-divider>样式设置</el-divider>

              <!-- 5. 分割线样式 -->
              <el-form-item label="线条样式">
                <el-select v-model="currentItem.props.borderStyle">
                  <el-option label="实线" value="solid" />
                  <el-option label="虚线" value="dashed" />
                </el-select>
              </el-form-item>

              <!-- 6. 背景颜色 -->
              <el-form-item label="背景颜色">
                <el-color-picker v-model="currentItem.props.backgroundColor" />
              </el-form-item>

              <!-- 7. 圆角设置 -->
              <el-form-item label="圆角">
                <el-input-number v-model="currentItem.props.borderRadius" :min="0" :max="20" />
              </el-form-item>
            </template>

            <!-- 其他组件的属性设置 -->
            <template v-else>
              <el-form-item label="标签">
                <el-input v-model="currentItem.label" />
              </el-form-item>
              <el-form-item label="字段名" v-if="currentItem.type !== 'row' && currentItem.type !== 'grid' && currentItem.type !== 'divider'">
                <el-input v-model="currentItem.field" />
              </el-form-item>
              <el-form-item label="占位文本" v-if="hasPlaceholder(currentItem)">
                <el-input v-model="currentItem.props.placeholder" />
              </el-form-item>
              
              <!-- 通用属性设置 -->
              <el-form-item label="必填">
                <el-switch v-model="currentItem.props.required" />
              </el-form-item>
              <el-form-item label="禁用">
                <el-switch v-model="currentItem.props.disabled" />
              </el-form-item>
              <el-form-item label="标签位置">
                <el-select v-model="currentItem.props.labelPosition">
                  <el-option label="顶部" value="top" />
                  <el-option label="左侧" value="left" />
                </el-select>
              </el-form-item>

              <!-- 尺寸设置 -->
              <el-divider>尺寸设置</el-divider>
              <el-form-item label="宽度">
                <el-select v-model="currentItem.props.widthType" class="width-type-select">
                  <el-option label="自适应" value="auto" />
                  <el-option label="固定像素" value="px" />
                  <el-option label="百分比" value="percent" />
                </el-select>
                <el-input-number 
                  v-if="currentItem.props.widthType !== 'auto'"
                  v-model="currentItem.props.width" 
                  :min="0"
                  :max="currentItem.props.widthType === 'percent' ? 100 : 2000"
                  :step="currentItem.props.widthType === 'percent' ? 5 : 10"
                  class="width-input"
                />
                <!-- <span v-if="currentItem.props.widthType === 'percent'">%</span>
                <span v-if="currentItem.props.widthType === 'px'">px</span> -->
              </el-form-item>
              <el-form-item label="高度">
                <el-select v-model="currentItem.props.heightType" class="height-type-select">
                  <el-option label="自适应" value="auto" />
                  <el-option label="固定像素" value="px" />
                </el-select>
                <el-input-number 
                  v-if="currentItem.props.heightType !== 'auto'"
                  v-model="currentItem.props.height" 
                  :min="0"
                  :max="1000"
                  :step="10"
                  class="height-input"
                />
                <!-- <span v-if="currentItem.props.heightType === 'px'">px</span> -->
              </el-form-item>

              <!-- 样式设置 -->
              <el-divider>样式设置</el-divider>
              <el-form-item label="字体">
                <el-select v-model="currentItem.props.fontFamily">
                  <el-option label="默认" value="" />
                  <el-option label="微软雅黑" value="Microsoft YaHei" />
                  <el-option label="宋体" value="SimSun" />
                  <el-option label="黑体" value="SimHei" />
                  <el-option label="楷体" value="KaiTi" />
                </el-select>
              </el-form-item>
              <el-form-item label="字体大小">
                <el-input-number v-model="currentItem.props.fontSize" :min="12" :max="24" />
              </el-form-item>
              <el-form-item label="字体颜色">
                <el-color-picker v-model="currentItem.props.fontColor" />
              </el-form-item>
              <el-form-item label="背景颜色">
                <el-color-picker v-model="currentItem.props.backgroundColor" />
              </el-form-item>
              <el-form-item label="边框样式">
                <el-select v-model="currentItem.props.borderStyle">
                  <el-option label="无边框" value="none" />
                  <el-option label="实线" value="solid" />
                  <el-option label="虚线" value="dashed" />
                  <el-option label="点线" value="dotted" />
                  <el-option label="双线" value="double" />
                </el-select>
              </el-form-item>
              <el-form-item label="边框颜色" v-if="currentItem.props.borderStyle !== 'none'">
                <el-color-picker v-model="currentItem.props.borderColor" />
              </el-form-item>
              <el-form-item label="边框宽度" v-if="currentItem.props.borderStyle !== 'none'">
                <el-input-number v-model="currentItem.props.borderWidth" :min="0" :max="4" />
              </el-form-item>
              <el-form-item label="圆角" v-if="currentItem.props.borderStyle !== 'none'">
                <el-input-number v-model="currentItem.props.borderRadius" :min="0" :max="20" />
              </el-form-item>
              <el-form-item label="内边距">
                <el-input-number v-model="currentItem.props.padding" :min="0" :max="20" />
              </el-form-item>
              <el-form-item label="外边距">
                <el-input-number v-model="currentItem.props.margin" :min="0" :max="20" />
              </el-form-item>

              <!-- 输入框属性 -->
              <template v-if="currentItem.type === 'input'">
                <el-form-item label="类型">
                  <el-select v-model="currentItem.props.type">
                    <el-option label="文本" value="text" />
                    <el-option label="密码" value="password" />
                    <el-option label="数字" value="number" />
                    <el-option label="邮箱" value="email" />
                    <el-option label="手机号" value="tel" />
                  </el-select>
                </el-form-item>
                <el-form-item label="最大长度">
                  <el-input-number v-model="currentItem.props.maxlength" :min="0" />
                </el-form-item>
                <el-form-item label="显示计数">
                  <el-switch v-model="currentItem.props.showWordLimit" />
                </el-form-item>
                <el-form-item label="清除按钮">
                  <el-switch v-model="currentItem.props.clearable" />
                </el-form-item>
                <el-form-item label="前缀图标">
                  <el-input v-model="currentItem.props.prefixIcon" placeholder="输入图标名称" />
                </el-form-item>
                <el-form-item label="后缀图标">
                  <el-input v-model="currentItem.props.suffixIcon" placeholder="输入图标名称" />
                </el-form-item>
              </template>

              <!-- 文本域属性 -->
              <template v-if="currentItem.type === 'textarea'">
                <el-form-item label="行数">
                  <el-input-number v-model="currentItem.props.rows" :min="2" />
                </el-form-item>
                <el-form-item label="自适应">
                  <el-switch v-model="currentItem.props.autosize" />
                </el-form-item>
              </template>

              <!-- 数字输入框属性 -->
              <template v-if="currentItem.type === 'number'">
                <el-form-item label="最小值">
                  <el-input-number v-model="currentItem.props.min" />
                </el-form-item>
                <el-form-item label="最大值">
                  <el-input-number v-model="currentItem.props.max" />
                </el-form-item>
                <el-form-item label="步长">
                  <el-input-number v-model="currentItem.props.step" :min="0" :step="0.1" />
                </el-form-item>
                <el-form-item label="精度">
                  <el-input-number v-model="currentItem.props.precision" :min="0" :max="10" />
                </el-form-item>
              </template>

              <!-- 选择器属性 -->
              <template v-if="currentItem.type === 'select'">
                <el-form-item label="数据来源">
                  <el-select v-model="currentItem.props.dataSource">
                    <el-option label="静态数据" value="static" />
                    <el-option label="API接口" value="api" />
                    <el-option label="数据库" value="database" />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="currentItem.props.dataSource === 'api'" label="API地址">
                  <el-input v-model="currentItem.props.apiUrl" placeholder="请输入API地址" />
                </el-form-item>
                <el-form-item v-if="currentItem.props.dataSource === 'database'" label="数据表">
                  <el-input v-model="currentItem.props.tableName" placeholder="请输入数据表名" />
                </el-form-item>
                <el-form-item v-if="currentItem.props.dataSource === 'database'" label="值字段">
                  <el-input v-model="currentItem.props.valueField" placeholder="请输入值字段名" />
                </el-form-item>
                <el-form-item v-if="currentItem.props.dataSource === 'database'" label="标签字段">
                  <el-input v-model="currentItem.props.labelField" placeholder="请输入标签字段名" />
                </el-form-item>
                <el-form-item label="多选">
                  <el-switch v-model="currentItem.props.multiple" />
                </el-form-item>
                <el-form-item label="可搜索">
                  <el-switch v-model="currentItem.props.filterable" />
                </el-form-item>
                <el-form-item label="选项">
                  <div class="option-list">
                    <div v-for="(option, idx) in currentItem.props.options" :key="idx" class="option-item">
                      <el-input v-model="option.label" placeholder="选项名" class="option-input" size="default" />
                      <el-input v-model="option.value" placeholder="选项值" class="option-input" size="default" />
                      <el-button type="danger" link @click="removeOption(idx)" size="default">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                  <div style="margin-top: 8px;">
                    <el-button type="primary" link @click="addOption" size="default">
                      <el-icon><Plus /></el-icon>添加选项
                    </el-button>
                  </div>
                </el-form-item>
              </template>

              <!-- 日期选择器属性 -->
              <template v-if="currentItem.type === 'date'">
                <el-form-item label="类型">
                  <el-select v-model="currentItem.props.type">
                    <el-option label="日期" value="date" />
                    <el-option label="日期时间" value="datetime" />
                    <el-option label="月份" value="month" />
                    <el-option label="年份" value="year" />
                    <el-option label="周" value="week" />
                  </el-select>
                </el-form-item>
                <el-form-item label="范围选择">
                  <el-switch v-model="currentItem.props.isRange" />
                </el-form-item>
                <el-form-item label="格式">
                  <el-input v-model="currentItem.props.format" />
                </el-form-item>
              </template>

              <!-- 开关属性 -->
              <template v-if="currentItem.type === 'switch'">
                <el-form-item label="打开值">
                  <el-input v-model="currentItem.props.activeValue" />
                </el-form-item>
                <el-form-item label="关闭值">
                  <el-input v-model="currentItem.props.inactiveValue" />
                </el-form-item>
                <el-form-item label="打开文本">
                  <el-input v-model="currentItem.props.activeText" />
                </el-form-item>
                <el-form-item label="关闭文本">
                  <el-input v-model="currentItem.props.inactiveText" />
                </el-form-item>
              </template>

              <!-- 滑块属性 -->
              <template v-if="currentItem.type === 'slider'">
                <el-form-item label="最小值">
                  <el-input-number v-model="currentItem.props.min" />
                </el-form-item>
                <el-form-item label="最大值">
                  <el-input-number v-model="currentItem.props.max" />
                </el-form-item>
                <el-form-item label="步长">
                  <el-input-number v-model="currentItem.props.step" :min="0" />
                </el-form-item>
                <el-form-item label="显示标记">
                  <el-switch v-model="currentItem.props.showStops" />
                </el-form-item>
              </template>

              <!-- 评分属性 -->
              <template v-if="currentItem.type === 'rate'">
                <el-form-item label="最大值">
                  <el-input-number v-model="currentItem.props.max" :min="1" :max="10" />
                </el-form-item>
                <el-form-item label="允许半选">
                  <el-switch v-model="currentItem.props.allowHalf" />
                </el-form-item>
                <el-form-item label="显示分数">
                  <el-switch v-model="currentItem.props.showScore" />
                </el-form-item>
              </template>

              <!-- 颜色选择器属性 -->
              <template v-if="currentItem.type === 'color'">
                <el-form-item label="显示透明度">
                  <el-switch v-model="currentItem.props.showAlpha" />
                </el-form-item>
                <el-form-item label="预定义颜色">
                  <el-input v-model="currentItem.props.predefine" type="textarea" rows="3" placeholder="输入颜色值，用逗号分隔" />
                </el-form-item>
              </template>

              <!-- 栅格布局属性 -->
              <template v-if="currentItem.type === 'grid'">
                <el-form-item label="列间距">
                  <el-input-number v-model="currentItem.props.gutter" :min="0" :max="40" />
                </el-form-item>
                <el-form-item label="对齐方式">
                  <el-select v-model="currentItem.props.justify">
                    <el-option label="左对齐" value="start" />
                    <el-option label="右对齐" value="end" />
                    <el-option label="居中" value="center" />
                    <el-option label="两端对齐" value="space-between" />
                    <el-option label="环绕对齐" value="space-around" />
                  </el-select>
                </el-form-item>
                <el-form-item label="垂直对齐">
                  <el-select v-model="currentItem.props.align">
                    <el-option label="顶部对齐" value="top" />
                    <el-option label="居中对齐" value="middle" />
                    <el-option label="底部对齐" value="bottom" />
                  </el-select>
                </el-form-item>
                <el-form-item label="布局类型">
                  <el-select v-model="currentItem.props.type">
                    <el-option label="弹性布局" value="flex" />
                    <el-option label="块级布局" value="block" />
                  </el-select>
                </el-form-item>
                <el-form-item label="列数">
                  <el-input-number 
                    v-model="currentItem.props.cols" 
                    :min="1" 
                    :max="24"
                    @change="watchCols(currentItem)"
                  />
                </el-form-item>
              </template>

              <!-- 复选框组属性 -->
              <template v-if="currentItem.type === 'checkbox'">
                <el-form-item label="数据来源">
                  <el-select v-model="currentItem.props.dataSource">
                    <el-option label="静态数据" value="static" />
                    <el-option label="API接口" value="api" />
                    <el-option label="数据库" value="database" />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="currentItem.props.dataSource === 'api'" label="API地址">
                  <el-input v-model="currentItem.props.apiUrl" placeholder="请输入API地址" />
                </el-form-item>
                <el-form-item v-if="currentItem.props.dataSource === 'database'" label="数据表">
                  <el-input v-model="currentItem.props.tableName" placeholder="请输入数据表名" />
                </el-form-item>
                <el-form-item v-if="currentItem.props.dataSource === 'database'" label="值字段">
                  <el-input v-model="currentItem.props.valueField" placeholder="请输入值字段名" />
                </el-form-item>
                <el-form-item v-if="currentItem.props.dataSource === 'database'" label="标签字段">
                  <el-input v-model="currentItem.props.labelField" placeholder="请输入标签字段名" />
                </el-form-item>
                <el-form-item label="显示全选">
                  <el-switch v-model="currentItem.props.showCheckAll" />
                </el-form-item>
                <el-form-item label="选项">
                  <div class="option-list">
                    <div v-for="(option, idx) in currentItem.props.options" :key="idx" class="option-item">
                      <el-input v-model="option.label" placeholder="选项名" class="option-input" size="default" />
                      <el-input v-model="option.value" placeholder="选项值" class="option-input" size="default" />
                      <el-button type="danger" link @click="removeOption(idx)" size="default">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                  <div style="margin-top: 8px;">
                    <el-button type="primary" link @click="addOption" size="default">
                      <el-icon><Plus /></el-icon>添加选项
                    </el-button>
                  </div>
                </el-form-item>
              </template>
            </template>
          </el-form>
        </el-card>
        <el-empty v-else description="请选择组件" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import {
  Check,
  Back,
  Plus,
  Setting,
  Delete,
  ArrowUp,
  ArrowDown,
  Edit,
  Calendar,
  Switch,
  Select,
  Document,
  Search,
  Upload,
  Star,
  Brush,
  ArrowLeft,
  ArrowRight,
  Rank,
  Right
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 组件分组配置
const componentGroups = [
  {
    title: '布局组件',
    items: [
      { type: 'row', label: '行容器', icon: 'Setting', component: 'div', props: { items: [], gutter: 20 } },
      // { type: 'grid', label: '栅格布局', icon: 'Setting', component: 'el-row', props: {} },
      { type: 'divider', label: '分割线', icon: 'Setting', component: 'el-divider', props: {} }
    ]
  },
  {
    title: '基础组件',
    items: [
      { type: 'input', label: '单行文本', icon: 'Edit', component: 'el-input', props: { placeholder: '请输入',maxlength: 100,showWordLimit: true, clearable: true } },
      { type: 'textarea', label: '多行文本', icon: 'Document', component: 'el-input', props: { type: 'textarea', rows: 3,placeholder: '请输入',maxlength: 100,showWordLimit: true, clearable: true } },
      { type: 'number', label: '数字输入', icon: 'Edit', component: 'el-input-number', props: { controls: true,min: 0,max: 100,step: 1,precision: 0 } },
      { type: 'select', label: '下拉选择', icon: 'Select', component: 'el-select', props: { options: [],multiple: false,filterable: false } },
      { type: 'radio', label: '单选框组', icon: 'Select', component: 'el-radio-group', props: { options: [],multiple: false,filterable: false } },
      { type: 'checkbox', label: '复选框组', icon: 'Select', component: 'el-checkbox-group', props: { options: [],min: 0,max: 0,showCheckAll: true } },
      { type: 'switch', label: '开关', icon: 'Switch', component: 'el-switch', props: {activeValue: true,inactiveValue: false,activeText: '是',inactiveText: '否'} },
      { type: 'slider', label: '滑块', icon: 'Setting', component: 'el-slider', props: {min: 0,max: 100,step: 1,showStops: false} }
    ]
  },
  {
    title: '高级组件',
    items: [
      { type: 'date', label: '日期选择', icon: 'Calendar', component: 'el-date-picker', props: {} },
      { type: 'time', label: '时间选择', icon: 'Calendar', component: 'el-time-picker', props: {} },
      { type: 'rate', label: '评分', icon: 'Star', component: 'el-rate', props: {} },
      { type: 'color', label: '颜色选择', icon: 'Brush', component: 'el-color-picker', props: {} },
      { type: 'upload', label: '文件上传', icon: 'Upload', component: 'el-upload', props: {} }
    ]
  }
]

const props = defineProps<{
  form: {
    id: string
    name: string
    type?: string
    folderId?: string
  }
}>()

const emit = defineEmits(['back', 'save'])

const formTitle = ref(props.form?.name || '')

interface ComponentProps {
  [key: string]: any
}

interface FormItem {
  type: string
  label: string
  field: string
  props: any
  component: string
  icon?: string
}

const formItems = ref<FormItem[]>([])
const currentItem = ref<FormItem | null>(null)

// 配置后端API基础URL
const API_BASE_URL = 'http://localhost:5000/api'

// 表单设计数据
const formData = ref({
  components: [],
  layout: {},
  settings: {},
  name: props.form?.name || ''
})

const formAreaRef = ref<HTMLElement | null>(null)
const itemRefs = ref<HTMLElement[]>([])

// 设置组件引用
const setItemRef = (el: HTMLElement | null, index: number) => {
  if (el) {
    itemRefs.value[index] = el
  }
}

// 获取组件位置信息
const getItemPosition = (index: number) => {
  const item = itemRefs.value[index]
  if (!item) return null
  
  const rect = item.getBoundingClientRect()
  return {
    top: rect.top,
    bottom: rect.bottom,
    height: rect.height
  }
}

// 加载表单数据
const loadFormData = async () => {
  try {
    // 检查表单ID是否存在
    if (!props.form?.id) {
      ElMessage.error('表单ID不存在')
      return
    }

    // 确保表单ID格式正确
    const formId = props.form.id.startsWith('form_') ? props.form.id : `${props.form.id}`
    
    const response = await axios.get(`${API_BASE_URL}/form/${formId}`)
    if (response.data.code === 0) {
      formData.value = response.data.data
      formTitle.value = formData.value.name || props.form?.name || ''
      formItems.value = formData.value.components || []
      ElMessage.success('表单数据加载成功')
    } else {
      // 如果表单不存在，使用默认空数据
      if (response.status === 404) {
        formData.value = {
          components: [],
          layout: {},
          settings: {},
          name: props.form?.name || ''
        }
        formItems.value = []
      } else {
        ElMessage.error(response.data.message || '加载表单数据失败')
      }
    }
  } catch (error) {
    console.error('加载表单数据错误:', error)
    // 如果是404错误，使用默认空数据
    if (error.response?.status === 404) {
      formData.value = {
        components: [],
        layout: {},
        settings: {},
        name: props.form?.name || ''
      }
      formItems.value = []
    } else {
      ElMessage.error('加载表单数据失败，请检查网络连接')
    }
  }
}

// 保存表单数据
const handleSave = async () => {
  try {
    // 检查表单ID是否存在
    if (!props.form?.id) {
      ElMessage.error('表单ID不存在')
      return
    }

    // 更新表单名称
    formData.value.name = formTitle.value
    
    // 确保表单数据包含必要的字段
    const saveData = {
      ...formData.value,
      components: formItems.value,
      id: props.form.id,
      name: formTitle.value
    }
    
    const response = await axios.post(`${API_BASE_URL}/form/${props.form.id}`, saveData)
    if (response.data.code === 0) {
      ElMessage.success('表单保存成功')
      emit('save', saveData)
    } else {
      ElMessage.error(response.data.message || '保存表单失败')
    }
  } catch (error) {
    console.error('保存表单数据错误:', error)
    ElMessage.error('保存表单失败，请检查网络连接')
  }
}

// 在组件挂载时加载表单数据
onMounted(() => {
  if (props.form?.id) {
    loadFormData()
  } else {
    // 如果是新建表单，初始化空数据
    formData.value = {
      components: [],
      layout: {},
      settings: {},
      name: formTitle.value
    }
  }
  // 添加初始状态到历史记录
  addToHistory()
})

// 处理拖拽开始
const handleDragStart = (event, item) => {
  event.dataTransfer.setData('componentType', item.type)
}

// 计算组件样式
const getComponentStyle = (item) => {
  const style = {
    fontFamily: item.props.fontFamily,
    fontSize: item.props.fontSize + 'px',
    color: item.props.fontColor,
    backgroundColor: item.props.backgroundColor,
    padding: item.props.padding + 'px',
    margin: item.props.margin + 'px'
  }

  // 只有在边框样式不为 none 时才添加边框相关样式
  if (item.props.borderStyle !== 'none') {
    style.borderStyle = item.props.borderStyle
    style.borderColor = item.props.borderColor
    style.borderWidth = item.props.borderWidth + 'px'
    style.borderRadius = item.props.borderRadius + 'px'
  } else {
    style.border = 'none'
  }

  // 添加宽度设置
  if (item.props.widthType === 'px') {
    style.width = `${item.props.width}px`
  } else if (item.props.widthType === 'percent') {
    style.width = `${item.props.width}%`
  }

  // 添加高度设置
  if (item.props.heightType === 'px') {
    style.height = `${item.props.height}px`
  }

  return style
}

// 在组件初始化时添加尺寸属性
const initializeComponentProps = (type) => {
  const baseProps = {
    widthType: 'auto',
    width: 100,
    heightType: 'auto',
    height: 32,
    fontFamily: 'Microsoft YaHei',
    fontSize: 14,
    fontColor: '#606266',
    backgroundColor: '#ffffff',
    borderStyle: 'none', // 修改默认边框样式为无边框
    borderColor: '#DCDFE6',
    borderWidth: 1,
    borderRadius: 4,
    padding: 0,
    margin: 0,
    labelPosition: 'top'
  }

  switch (type) {
    case 'row':
      return {
        ...baseProps,
        items: [],
        gutter: 20,
        widthType: 'percent',
        width: 100
      }
    case 'input':
      return {
        ...baseProps,
        placeholder: '请输入',
        clearable: true,
        maxlength: undefined,
        showWordLimit: false,
        type: 'text',
        prefixIcon: '',
        suffixIcon: '',
        widthType: 'percent',
        width: 100
      }
    case 'textarea':
      return {
        ...baseProps,
        placeholder: '请输入',
        rows: 3,
        autosize: false,
        maxlength: undefined,
        showWordLimit: false,
        heightType: 'px',
        height: 100,
        widthType: 'percent',
        width: 100
      }
    case 'select':
      return {
        ...baseProps,
        placeholder: '请选择',
        clearable: true,
        multiple: false,
        filterable: false,
        dataSource: 'static',
        apiUrl: '',
        tableName: '',
        valueField: '',
        labelField: '',
        value: '',
        options: [
          { label: '选项1', value: '1' },
          { label: '选项2', value: '2' }
        ],
        widthType: 'percent',
        width: 100
      }
    case 'checkbox':
      return {
        ...baseProps,
        options: [
          { label: '选项1', value: '1' },
          { label: '选项2', value: '2' }
        ],
        value: [],
        checkAll: false,
        showCheckAll: true,
        dataSource: 'static',
        apiUrl: '',
        tableName: '',
        valueField: '',
        labelField: '',
        widthType: 'percent',
        width: 100
      }
    case 'divider':
      return {
        showLabel: true,
        fontFamily: '',
        fontSize: 14,
        fontColor: '#303133',
        backgroundColor: '#ffffff',
        borderStyle: 'solid',
        borderRadius: 0,
        widthType: 'auto',
        width: 100,
        labelPosition: 'left'
      }
    // ... 其他组件的初始化属性
    default:
      return baseProps
  }
}

// 处理拖拽放置
const handleDrop = (event: DragEvent) => {
  if (!formAreaRef.value) return
  
  const type = event.dataTransfer?.getData('componentType')
  const component = componentGroups
    .flatMap(group => group.items)
    .find(item => item.type === type)

  if (!component) return

  // 获取表单区域的边界
  const formAreaRect = formAreaRef.value.getBoundingClientRect()
  const dropY = event.clientY - formAreaRect.top

  // 计算插入位置
  let insertIndex = formItems.value.length
  for (let i = 0; i < formItems.value.length; i++) {
    const itemPos = getItemPosition(i)
    if (!itemPos) continue

    // 如果鼠标位置在当前组件中间位置以上，则插入到当前位置
    const itemMiddle = itemPos.top + (itemPos.height / 2)
    if (dropY < itemMiddle) {
      insertIndex = i
      break
    }
  }

  // 创建新组件
  const newItem = {
    ...component,
    field: `field_${formItems.value.length + 1}`,
    label: component.label,
    props: initializeComponentProps(type)
  }

  // 在指定位置插入组件
  formItems.value.splice(insertIndex, 0, newItem)
  selectItem(newItem)
}

// 选择组件
const selectItem = (item) => {
  currentItem.value = item
}

// 移动组件
const moveItem = (index, direction) => {
  const newIndex = index + direction
  if (newIndex >= 0 && newIndex < formItems.value.length) {
    const item = formItems.value.splice(index, 1)[0]
    formItems.value.splice(newIndex, 0, item)
  }
}

// 删除组件
const removeItem = (index) => {
  formItems.value.splice(index, 1)
  if (currentItem.value === formItems.value[index]) {
    currentItem.value = null
  }
}

// 监听选项变化，自动更新选中值
watch(() => currentItem.value?.props?.options, (newOptions) => {
  if (currentItem.value?.type === 'select' && newOptions) {
    // 如果当前值不在选项中，清空选中值
    if (currentItem.value.props.multiple) {
      // 多选模式
      if (Array.isArray(currentItem.value.props.value)) {
        currentItem.value.props.value = currentItem.value.props.value.filter(v => 
          newOptions.some(opt => opt.value === v)
        )
      } else {
        currentItem.value.props.value = []
      }
    } else {
      // 单选模式
      if (!newOptions.some(opt => opt.value === currentItem.value.props.value)) {
        currentItem.value.props.value = ''
      }
    }
  }
}, { deep: true })

// 监听多选模式变化
watch(() => currentItem.value?.props?.multiple, (newMultiple) => {
  if (currentItem.value?.type === 'select') {
    // 切换多选模式时重置值
    currentItem.value.props.value = newMultiple ? [] : ''
  }
}, { immediate: true })

// 添加选项
const addOption = () => {
  if (currentItem.value && currentItem.value.props.options) {
    const newOptionIndex = currentItem.value.props.options.length + 1
    currentItem.value.props.options.push({
      label: `选项${newOptionIndex}`,
      value: `${newOptionIndex}`
    })
  }
}

// 删除选项
const removeOption = (index) => {
  if (currentItem.value && currentItem.value.props.options) {
    currentItem.value.props.options.splice(index, 1)
    // 检查并更新选中值
    if (currentItem.value.type === 'select') {
      const options = currentItem.value.props.options
      if (currentItem.value.props.multiple) {
        // 多选模式
        if (Array.isArray(currentItem.value.props.value)) {
          currentItem.value.props.value = currentItem.value.props.value.filter(v => 
            options.some(opt => opt.value === v)
          )
        }
      } else {
        // 单选模式
        if (!options.some(opt => opt.value === currentItem.value.props.value)) {
          currentItem.value.props.value = ''
        }
      }
    }
  }
}

// 判断组件是否有placeholder属性
const hasPlaceholder = (item) => {
  return ['input', 'textarea', 'select', 'date'].includes(item.type)
}

// 处理返回
const handleBack = () => {
  ElMessageBox.confirm('确定要离开表单设计器吗？未保存的更改将会丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    emit('back')
  }).catch(() => {
    // 用户点击取消，不做任何操作
  })
}

// 处理栅格布局中的拖放
const handleGridDrop = (event, gridItem, colIndex) => {
  // 阻止事件冒泡
  event.stopPropagation()
  
  const type = event.dataTransfer.getData('componentType')
  const component = componentGroups
    .flatMap(group => group.items)
    .find(item => item.type === type)

  if (component) {
    const newItem = {
      ...component,
      field: `field_${formItems.value.length + 1}`,
      label: component.label,
      props: { ...component.props }
    }

    // 初始化组件属性
    switch (type) {
      case 'input':
        newItem.props = {
          ...newItem.props,
          placeholder: '请输入',
          clearable: true,
          maxlength: undefined,
          showWordLimit: false,
          type: 'text'
        }
        break
      case 'textarea':
        newItem.props = {
          ...newItem.props,
          placeholder: '请输入',
          rows: 3,
          autosize: false,
          maxlength: undefined,
          showWordLimit: false
        }
        break
      case 'select':
        newItem.props = {
          ...newItem.props,
          placeholder: '请选择',
          clearable: true,
          multiple: false,
          filterable: false,
          options: [
            { label: '选项1', value: '1' },
            { label: '选项2', value: '2' }
          ]
        }
        break
      case 'date':
        newItem.props = {
          ...newItem.props,
          type: 'date',
          placeholder: '请选择日期',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          isRange: false
        }
        break
      case 'switch':
        newItem.props = {
          ...newItem.props,
          activeValue: true,
          inactiveValue: false,
          activeText: '',
          inactiveText: ''
        }
        break
      case 'slider':
        newItem.props = {
          ...newItem.props,
          min: 0,
          max: 100,
          step: 1,
          showStops: false
        }
        break
      case 'rate':
        newItem.props = {
          ...newItem.props,
          max: 5,
          allowHalf: false,
          showScore: false
        }
        break
      case 'color':
        newItem.props = {
          ...newItem.props,
          showAlpha: false,
          predefine: []
        }
        break
      case 'checkbox':
        newItem.props = {
          ...newItem.props,
          options: [
            { label: '选项1', value: '1' },
            { label: '选项2', value: '2' }
          ],
          value: [],
          checkAll: false,
          min: 0,
          max: 0,
          showCheckAll: true,
          dataSource: 'static',
          apiUrl: '',
          tableName: '',
          valueField: '',
          labelField: '',
          // 通用样式属性
          fontFamily: '',
          fontSize: 14,
          fontColor: '#606266',
          backgroundColor: '#ffffff',
          borderStyle: 'solid',
          borderColor: '#DCDFE6',
          borderWidth: 1,
          borderRadius: 4,
          padding: 8,
          margin: 0
        }
        break
    }

    // 确保列数组存在
    if (!gridItem.props.children) {
      gridItem.props.children = Array(gridItem.props.cols).fill(null).map(() => ({
        span: 24 / gridItem.props.cols,
        items: []
      }))
    }

    // 确保当前列存在
    if (!gridItem.props.children[colIndex]) {
      gridItem.props.children[colIndex] = {
        span: 24 / gridItem.props.cols,
        items: []
      }
    }

    // 添加新组件到列中
    gridItem.props.children[colIndex].items.push(newItem)
    selectItem(newItem)
  }
}

// 移动栅格布局中的组件
const moveGridItem = (gridItem, colIndex, itemIndex, direction) => {
  const col = gridItem.props.children[colIndex]
  const newIndex = itemIndex + direction
  if (newIndex >= 0 && newIndex < col.items.length) {
    const item = col.items.splice(itemIndex, 1)[0]
    col.items.splice(newIndex, 0, item)
  }
}

// 删除栅格布局中的组件
const removeGridItem = (gridItem, colIndex, itemIndex) => {
  gridItem.props.children[colIndex].items.splice(itemIndex, 1)
  if (currentItem.value === gridItem.props.children[colIndex].items[itemIndex]) {
    currentItem.value = null
  }
}

// 添加监听列数变化的方法
const watchCols = (gridItem) => {
  const oldCols = gridItem.props.children.length
  const newCols = gridItem.props.cols
  
  if (newCols > oldCols) {
    // 增加列
    for (let i = oldCols; i < newCols; i++) {
      gridItem.props.children.push({
        span: 24 / newCols,
        items: []
      })
    }
  } else if (newCols < oldCols) {
    // 减少列
    gridItem.props.children = gridItem.props.children.slice(0, newCols)
  }
  
  // 更新所有列的 span
  gridItem.props.children.forEach(col => {
    col.span = 24 / newCols
  })
}

// 检查是否全部选中
const isAllChecked = (item) => {
  const values = item.props.value || []
  const options = item.props.options || []
  return options.length > 0 && values.length === options.length
}

// 检查是否部分选中
const isIndeterminate = (item) => {
  const values = item.props.value || []
  const options = item.props.options || []
  return values.length > 0 && values.length < options.length
}

// 修改处理全选变化的方法
const handleCheckAllChange = (val, item) => {
  item.props.checkAll = val
  if (val) {
    item.props.value = item.props.options.map(opt => opt.value)
  } else {
    item.props.value = []
  }
}

const handleSingleCheckChange = (item) => {
  // 更新全选状态
  if (item.props.options.length === 0) {
    item.props.checkAll = false
  } else {
    item.props.checkAll = item.props.value.length === item.props.options.length
  }
}

// 添加拖动相关的数据
const draggedItem = ref(null)
const draggedItemParent = ref(null)
const draggedItemIndex = ref(-1)
const draggedItemType = ref('')
const dropIndicator = ref(null)

// 处理组件拖动开始
const handleComponentDragStart = (event, item, index, type, parent = null) => {
  draggedItem.value = item
  draggedItemParent.value = parent
  draggedItemIndex.value = index
  draggedItemType.value = type
  
  // 设置拖动效果
  event.dataTransfer.effectAllowed = 'move'
  event.dataTransfer.setData('text/plain', '') // 必须设置数据，否则某些浏览器可能不允许拖动
  
  // 添加拖动样式
  event.target.classList.add('dragging')
}

// 处理组件拖动放置
const handleComponentDrop = (event, targetIndex, targetType, targetParent = null) => {
  event.preventDefault()
  
  // 如果没有拖动项，则返回
  if (!draggedItem.value) return
  
  // 移除所有拖动样式
  document.querySelectorAll('.form-item-wrapper').forEach(el => {
    el.classList.remove('drag-over')
  })
  
  // 处理不同情况的拖放
  if (draggedItemType.value === targetType) {
    // 同一容器内的拖放
    if (targetType === 'form') {
      // 主表单内的拖放
      const item = formItems.value.splice(draggedItemIndex.value, 1)[0]
      formItems.value.splice(targetIndex, 0, item)
    } else if (targetType === 'row' && draggedItemParent.value === targetParent) {
      // 行容器内的拖放
      const item = targetParent.props.items.splice(draggedItemIndex.value, 1)[0]
      targetParent.props.items.splice(targetIndex, 0, item)
    }
  } else {
    // 不同容器间的拖放
    if (targetType === 'row' && draggedItemType.value === 'form') {
      // 从主表单拖到行容器
      const item = formItems.value.splice(draggedItemIndex.value, 1)[0]
      targetParent.props.items.splice(targetIndex, 0, item)
    } else if (targetType === 'form' && draggedItemType.value === 'row') {
      // 从行容器拖到主表单
      const item = draggedItemParent.value.props.items.splice(draggedItemIndex.value, 1)[0]
      formItems.value.splice(targetIndex, 0, item)
    }
  }
  
  // 重置拖动状态
  draggedItem.value = null
  draggedItemParent.value = null
  draggedItemIndex.value = -1
  draggedItemType.value = ''
}

// 修改handleRowDrop方法以支持组件拖放
const handleRowDrop = (event, rowContainer) => {
  event.stopPropagation()
  
  // 处理从组件列表拖入的新组件
  const type = event.dataTransfer.getData('componentType')
  if (type) {
    const component = componentGroups
      .flatMap(group => group.items)
      .find(item => item.type === type)

    if (component && component.type !== 'row') {
      const totalComponents = formItems.value.reduce((total, item) => {
        if (item.type === 'row') {
          return total + (item.props.items?.length || 0)
        }
        return total + 1
      }, 0)

      const newItem = {
        ...component,
        field: `field_${totalComponents + 1}`,
        label: component.label,
        props: initializeComponentProps(type)
      }
      
      if (!rowContainer.props.items) {
        rowContainer.props.items = []
      }
      rowContainer.props.items.push(newItem)
      selectItem(newItem)
    }
  } else if (draggedItem.value) {
    // 处理已存在组件的拖放
    if (draggedItemType.value === 'form') {
      // 从主表单拖到行容器
      const item = formItems.value.splice(draggedItemIndex.value, 1)[0]
      if (!rowContainer.props.items) {
        rowContainer.props.items = []
      }
      rowContainer.props.items.push(item)
    }
  }
  
  // 重置拖动状态
  draggedItem.value = null
  draggedItemParent.value = null
  draggedItemIndex.value = -1
  draggedItemType.value = ''
}

// 删除行容器内的组件
const removeRowItem = (rowContainer, index) => {
  rowContainer.props.items.splice(index, 1)
  if (currentItem.value === rowContainer.props.items[index]) {
    currentItem.value = null
  }
}

// 在 script setup 中添加历史记录相关的状态
const history = ref([])
const currentHistoryIndex = ref(-1)

// 添加历史记录
const addToHistory = () => {
  // 删除当前位置之后的历史记录
  if (currentHistoryIndex.value < history.value.length - 1) {
    history.value = history.value.slice(0, currentHistoryIndex.value + 1)
  }
  
  // 添加新的历史记录
  history.value.push(JSON.stringify({
    formItems: formItems.value,
    formTitle: formTitle.value
  }))
  currentHistoryIndex.value++
}

// 撤销修改
const handleUndo = () => {
  if (currentHistoryIndex.value > 0) {
    currentHistoryIndex.value--
    const previousState = JSON.parse(history.value[currentHistoryIndex.value])
    formItems.value = previousState.formItems
    formTitle.value = previousState.formTitle
  }
}

// 重做修改
const handleRedo = () => {
  if (currentHistoryIndex.value < history.value.length - 1) {
    currentHistoryIndex.value++
    const nextState = JSON.parse(history.value[currentHistoryIndex.value])
    formItems.value = nextState.formItems
    formTitle.value = nextState.formTitle
  }
}

// 监听表单变化，添加到历史记录
watch([formItems, formTitle], () => {
  addToHistory()
}, { deep: true })
</script>

<style scoped>
.form-designer {
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 13px;
}

.designer-header {
  padding: 8px 16px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  gap: 12px;
  background-color: #fff;
}

.designer-header .el-button-group {
  margin-right: 8px;
}

.title-input {
  width: 300px;
}

.designer-container {
  flex: 1;
  display: flex;
  overflow: hidden;
  background-color: #f5f7fa;
}

.components-list {
  width: 280px;
  padding: 12px;
  border-right: 1px solid #dcdfe6;
  overflow-y: auto;
  background-color: #fff;
}

.component-group {
  margin-bottom: 16px;
  border: none;
  box-shadow: none;
}

.component-group:last-child {
  margin-bottom: 0;
}

.group-header {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
  padding: 0 4px;
  margin-bottom: 12px;
  border-left: 3px solid #409eff;
  padding-left: 8px;
}

.group-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 4px 0;
}

.component-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 12px 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: move;
  user-select: none;
  transition: all 0.2s ease;
  background-color: #fff;
  min-height: 12px;
}

.component-item:hover {
  border-color: #409eff;
  color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.component-item .el-icon {
  font-size: 12px;
  margin-bottom: 4px;
  color: #7fa3ec;
}

.component-item:hover .el-icon {
  color: #409eff;
}

.component-item span {
  font-size: 10px;
  color: #606266;
  text-align: center;
  line-height: 1.2;
}

.component-item:hover span {
  color: #409eff;
}

.form-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.design-form {
  max-width: 100%;
  margin: 0 auto;
  background-color: #fff;
  padding: 32px;
  border-radius: 8px;
  min-height: calc(100% - 40px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.form-item-wrapper {
  position: relative;
  padding: 1px 1px 1px 24px; /* 增加左侧padding以容纳拖动图标 */
  border: 1px dashed transparent;
  border-radius: 4px;
  transition: all 0.3s;
  margin-bottom: 1px;
  min-height: 50px;
}

/* 添加分割线组件的特殊样式 */
.form-item-wrapper:has(.el-divider) {
  margin: 5px 0;
  min-height: auto;
}

.form-item-wrapper:has(.el-divider) .el-divider {
  margin: 0;
}

/* 确保分割线组件不会与其他组件重叠 */
.form-item-wrapper:has(.el-divider) + .form-item-wrapper {
  margin-top: 5px;
}

.form-item-wrapper:hover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

.form-item-wrapper.is-active {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}

.form-item-actions {
  position: absolute;
  right: 12px;
  top: 12px;
  display: none;
  z-index: 1;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 4px;
}

.form-item-wrapper:hover .form-item-actions {
  display: flex;
  gap: 4px;
}

.properties-panel {
  width: 300px;
  padding: 20px;
  border-left: 1px solid #dcdfe6;
  overflow-y: auto;
  background-color: #fff;
}

.panel-header {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
  padding: 0 4px;
  margin-bottom: 16px;
  border-left: 3px solid #409eff;
  padding-left: 8px;
}

.option-item {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  align-items: center;
}

.option-input {
  flex: 1;
}

/* 添加新的样式 */
.option-item {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
  width: 100%;
}

.option-item .option-input {
  flex: 1;
  min-width: 120px; /* 设置最小宽度 */
}

.option-item .el-input {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-checkbox) {
  margin-right: 0;
  margin-left: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

/* 确保属性面板中的输入框和选择器样式正确 */
.properties-panel {
  .el-form-item {
    margin-bottom: 18px;
    
    .el-input,
    .el-select,
    .el-input-number {
      width: 100%;
    }
  }
  
  .option-item {
    .el-input {
      flex: 1;
      /* min-width: 0; */
    }
    
    .el-button {
      flex-shrink: 0;
    }
  }
}

/* 调整选项编辑区域的样式 */
.option-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 8px;
}

/* 确保下拉按钮可见 */
:deep(.el-input__suffix) {
  right: 5px;
  pointer-events: auto;
}

:deep(.el-input__inner) {
  padding-right: 30px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-size: 13px;
  color: #606266;
  padding: 0;
  width: 100px;
  text-align: left;
}

:deep(.el-form-item__content) {
  flex: 1;
  margin-left: 0 !important;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__wrapper),
:deep(.el-select__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__wrapper:hover),
:deep(.el-select__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-textarea__wrapper.is-focus),
:deep(.el-select__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 12px;
}

:deep(.el-card__header) {
  padding: 8px 12px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 12px;
}

:deep(.el-switch) {
  --el-switch-on-color: #409eff;
  --el-switch-off-color: #dcdfe6;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-date-editor) {
  width: 100%;
}

:deep(.el-color-picker) {
  width: 100%;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-rate) {
  --el-rate-icon-size: 16px;
}

:deep(.el-slider) {
  --el-slider-main-height: 4px;
  --el-slider-runway-height: 4px;
  --el-slider-button-size: 12px;
}

.grid-container {
  min-height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 8px;
}

.grid-col {
  min-height: 50px;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 8px;
}

.grid-col-content {
  min-height: 40px;
}

.grid-col:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.checkbox-group-container {
  width: 100%;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 12px;
  background-color: #fff;
}

.checkbox-all {
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px solid #EBEEF5;
}

.checkbox-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-checkbox) {
  margin-right: 0;
  margin-left: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

:deep(.el-checkbox__input) {
  pointer-events: auto;
}

:deep(.el-checkbox__label) {
  pointer-events: auto;
}

:deep(.el-checkbox.is-disabled) {
  cursor: pointer;
}

:deep(.el-checkbox.is-disabled .el-checkbox__input) {
  cursor: pointer;
}

:deep(.el-checkbox.is-disabled .el-checkbox__label) {
  cursor: pointer;
}

.width-type-select,
.height-type-select {
  width: 100px;
  margin-right: 8px;
}

.width-input,
.height-input {
  width: 100px;
}

.el-divider {
  margin: 16px 0;
}

:deep(.el-divider__text) {
  font-size: 13px;
  color: #909399;
  background-color: #ffffff;
}

:deep(.el-select) {
  width: 100%;
  display: block;
}

:deep(.el-select .el-input) {
  width: 100%;
}

:deep(.el-select__tags) {
  width: 100%;
  flex-wrap: wrap;
}

.option-item {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
  width: 100%;
}

.option-item .option-input {
  flex: 1;
  min-width: 120px;
}

.option-item .el-button {
  flex-shrink: 0;
}

.row-container {
  display: flex;
  flex-wrap: nowrap;
  gap: 20px;
  align-items: flex-start;
  margin-bottom: 22px;
  min-height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 8px;
  background-color: #fff;
}

.row-item-wrapper {
  flex: 1;
  min-width: 0;
  min-height: 50px;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  padding: 8px;
  position: relative;
}

.row-item-wrapper:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.row-item-wrapper.is-active {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}

.row-item-wrapper :deep(.el-form-item) {
  margin-bottom: 0;
}

.row-item-wrapper :deep(.el-form-item__content) {
  width: 100%;
}

.row-item-wrapper .form-item-actions {
  position: absolute;
  top: -30px;
  right: 0;
  z-index: 1;
  display: none;
}

.row-item-wrapper:hover .form-item-actions {
  display: block;
}

:deep(.label-top) {
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

:deep(.label-top .el-form-item__label) {
  text-align: left;
  padding: 0 0 8px 0;
  margin: 0;
  width: 100%;
}

:deep(.label-left) {
  display: flex;
  flex-direction: row;
  align-items: center;
}

:deep(.label-left .el-form-item__label) {
  text-align: right;
  padding: 0 12px 0 0;
  width: 100px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-form-item__content) {
  flex: 1;
}

.drag-indicator {
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
  cursor: move;
  opacity: 0;
  transition: opacity 0.2s;
  z-index: 2;
}

.form-item-wrapper:hover .drag-indicator {
  opacity: 1;
}

.drag-indicator .el-icon {
  font-size: 16px;
  color: #909399;
}

.form-item-wrapper.dragging {
  opacity: 0.5;
  border: 1px dashed #409eff;
}

.form-item-wrapper.drag-over {
  border: 2px dashed #409eff;
  position: relative;
}

.form-item-wrapper.drag-over::before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: -2px;
  height: 2px;
  background-color: #409eff;
}

.row-container.drag-over {
  border: 2px dashed #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}

.row-item-wrapper.drag-over {
  border: 2px dashed #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}
</style> 